import path from 'path';
import fs from 'fs';

// 存储配置
export const storageConfig = {
  // 基础上传目录
  baseUploadDir: 'uploads',
  
  // 临时文件目录
  tempDir: 'uploads/temp',
  
  // 文件组织方式
  organization: {
    // 按日期组织
    byDate: true,
    // 按文件类型组织
    byType: true,
    // 日期格式
    dateFormat: 'YYYY/MM/DD',
  },
  
  // 各类型文件的子目录
  typeDirs: {
    image: 'images',
    document: 'documents',
    presentation: 'presentations',
    spreadsheet: 'spreadsheets',
    archive: 'archives',
    video: 'videos',
    audio: 'audios',
    unknown: 'others'
  }
};

// 获取当前日期路径
export const getDatePath = (): string => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  
  return `${year}/${month}/${day}`;
};

// 获取文件存储路径
export const getStoragePath = (category: string): string => {
  const parts = [storageConfig.baseUploadDir];
  
  // 按类型组织
  if (storageConfig.organization.byType) {
    const typeDir = storageConfig.typeDirs[category as keyof typeof storageConfig.typeDirs] || storageConfig.typeDirs.unknown;
    parts.push(typeDir);
  }
  
  // 按日期组织
  if (storageConfig.organization.byDate) {
    parts.push(getDatePath());
  }
  
  return path.join(...parts);
};

// 确保目录存在
export const ensureDirectoryExists = (dirPath: string): void => {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
};

// 初始化存储目录
export const initializeStorageDirectories = (): void => {
  // 创建基础目录
  ensureDirectoryExists(storageConfig.baseUploadDir);
  ensureDirectoryExists(storageConfig.tempDir);
  
  // 创建类型子目录
  if (storageConfig.organization.byType) {
    Object.values(storageConfig.typeDirs).forEach(dir => {
      const dirPath = path.join(storageConfig.baseUploadDir, dir);
      ensureDirectoryExists(dirPath);
    });
  }
};

// 生成唯一文件名
export const generateUniqueFilename = (originalname: string, userId?: string): string => {
  const timestamp = Date.now();
  const random = Math.round(Math.random() * 1E9);
  const ext = path.extname(originalname).toLowerCase();
  const basename = path.basename(originalname, ext).replace(/[^a-zA-Z0-9]/g, '-');
  
  if (userId) {
    return `${userId}-${basename}-${timestamp}-${random}${ext}`;
  }
  
  return `${basename}-${timestamp}-${random}${ext}`;
};

// 获取文件的相对URL路径
export const getFileUrl = (filePath: string): string => {
  // 移除绝对路径前缀，只保留相对于uploads的路径
  const relativePath = filePath.replace(/\\/g, '/');
  const uploadsIndex = relativePath.indexOf('uploads/');
  
  if (uploadsIndex !== -1) {
    return '/' + relativePath.substring(uploadsIndex);
  }
  
  return '/' + relativePath;
};

// 清理临时文件
export const cleanupTempFiles = async (maxAge: number = 24 * 60 * 60 * 1000): Promise<void> => {
  try {
    const tempDir = storageConfig.tempDir;
    if (!fs.existsSync(tempDir)) {
      return;
    }
    
    const files = fs.readdirSync(tempDir);
    const now = Date.now();
    
    for (const file of files) {
      const filePath = path.join(tempDir, file);
      const stats = fs.statSync(filePath);
      
      if (now - stats.mtimeMs > maxAge) {
        fs.unlinkSync(filePath);
        console.log(`Deleted temp file: ${file}`);
      }
    }
  } catch (error) {
    console.error('Error cleaning up temp files:', error);
  }
};